package com.centerm.structure.api;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.centerm.common.constant.Constant;
import com.centerm.common.constant.error.GlobalErrorEnum;
import com.centerm.common.constant.validate.Delete;
import com.centerm.common.constant.validate.Insert;
import com.centerm.common.constant.validate.Update;
import com.centerm.common.view.JSONResponse;
import com.centerm.common.view.page.DefaultPage;
import com.centerm.common.view.page.PageQueryParam;
import com.centerm.common.view.page.PageQueryResult;
import com.centerm.structure.domain.Department;
import com.centerm.structure.dto.DepartmentInfo;
import com.centerm.structure.dto.DepartmentTreeInfo;
import com.centerm.structure.service.DepartmentService;
import com.centerm.structure.service.UserService;

@RestController
@RequestMapping("department")
public class DepartmentAPI extends AbstractAPI {
    
    @Autowired
    private UserService userService;
	@Autowired
	private DepartmentService departmentService;

	/**
	 * 根据条件分页查询部门列表
	 * 
	 * @author czy
	 * @date 2017年8月14日
	 * @param
	 * @return
	 */
	@PostMapping("page/byParam")
	public JSONResponse<PageQueryResult<DepartmentInfo>> pageDepartmentByParam(
			@RequestBody PageQueryParam<DepartmentInfo> param) {
		DefaultPage page = param.getPage();
		DepartmentInfo departmentInfo = param.getParam();
		if (page == null || departmentInfo == null) {
			// 参数检查异常
			logger.debug("PARAM_ERROR：" + param.toString());
			return new JSONResponse<>(GlobalErrorEnum.PARAM_ERROR);
		}
		// 分页查询
		PageQueryResult<DepartmentInfo> queryResult = departmentService
				.pageDepartmentInfoList(
						page.getPageNum() == null ? Constant.DEFAULT_PAGENUM
								: page.getPageNum(),
						page.getPageSize() == null ? Constant.DEFAULT_PAGESIZE
								: page.getPageSize(), departmentInfo);
		return success(queryResult);
	}

	/**
	 * 新增部门信息
	 * 
	 * @author czy
	 * @date 2017年8月11日
	 * @param DepartmentInfo
	 *            :部门信息
	 * @return 部门id
	 */
	@PostMapping("insert")
	public JSONResponse<Integer> insert(HttpSession httpSession,
			@RequestBody @Validated(Insert.class) DepartmentInfo departmentInfo) {
//		if (!departmentService.isManagerOfDeparment(httpSession, departmentInfo.getParentId())) {
//			logger.error(GlobalErrorEnum.NO_PERMISSIONS.getMsg());
//			return new JSONResponse<>(GlobalErrorEnum.NO_PERMISSIONS);
//		}
		Integer result = departmentService.insert(departmentInfo);
		if (result == null || result < 1) {
			logger.error("新增部门异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(result);
		}
	}

	/**
	 * @Description: 更新部门信息
	 * @author czy
	 * @date 2017年8月11日
	 * @param DepartmentInfo
	 *            部门信息
	 * @return JSONResponse<Integer>
	 */
	@PostMapping("update")
	public JSONResponse<Integer> update(
			HttpSession httpSession,
			@RequestBody @Validated(Update.class) DepartmentInfo departmentRequest) {
//		if (!departmentService.isManagerOfDeparment(httpSession, departmentRequest.getId())) {
//			logger.error(GlobalErrorEnum.NO_PERMISSIONS.getMsg());
//			return new JSONResponse<>(GlobalErrorEnum.NO_PERMISSIONS);
//		}
		Integer result = departmentService.update(departmentRequest);
		if (result != 1) {
			logger.error("更新部门异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(result);
		}
	}

	/**
	 * @Description: 物理删除部门
	 * @author czy
	 * @date 2017年7月26日
	 * @param id
	 *            部门id
	 * @return JSONResponse<Integer>
	 */
	@PostMapping("delete/physic")
	public JSONResponse<Integer> deletePhysic(
			HttpSession httpSession,
			@RequestBody @Validated(Delete.class) DepartmentInfo departmentRequest) {
//		if (!departmentService.isManagerOfDeparment(httpSession, departmentRequest.getId())) {
//			logger.error(GlobalErrorEnum.NO_PERMISSIONS.getMsg());
//			return new JSONResponse<>(GlobalErrorEnum.NO_PERMISSIONS);
//		}
		Integer result = departmentService.delete(departmentRequest.getId());
		if (result != 1) {
			logger.error("物理删除部门异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(result);
		}
	}

	/**
	 * @Description: 逻辑删除部门
	 * @author czy
	 * @date 2017年7月26日
	 * @param id
	 *            部门id
	 * @return JSONResponse<Integer>
	 */
	@PostMapping("delete/logic")
	public JSONResponse<Integer> deleteLogic(
			HttpSession httpSession,
			@RequestBody @Validated(Delete.class) DepartmentInfo departmentRequest) {
//		if (!departmentService.isManagerOfDeparment(httpSession, departmentRequest.getId())) {
//			logger.error(GlobalErrorEnum.NO_PERMISSIONS.getMsg());
//			return new JSONResponse<>(GlobalErrorEnum.NO_PERMISSIONS);
//		}
		departmentRequest.setValid(0);
		Integer result = departmentService.update(departmentRequest);
		if (result != 1) {
			logger.error("逻辑删除部门异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(result);
		}
	}

	/**
	 * @Description: 根据id获取部门详细信息
	 * @author czy
	 * @date 2017年8月11日
	 * @param id
	 *            部门id
	 * @return DepartmentInfo
	 */
	@PostMapping("getById")
	public JSONResponse<DepartmentInfo> getById(
			@RequestBody DepartmentInfo departmentInfo) {
		Integer departmentId = departmentInfo.getId();
		if (departmentId == null) {
			logger.error("获取部门详细信息异常：" + GlobalErrorEnum.PARAM_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.PARAM_ERROR);
		}
		departmentInfo = departmentService.getById(departmentId);
		if (departmentInfo == null) {
			logger.error("获取部门详细信息异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(departmentInfo);
		}
	}

	/**
	 * @Description: 获得所有部门和人员---树结构形式
	 * @author czy
	 * @date 2017年8月15日
	 * @param id
	 *            :部门id,0为顶层节点
	 * @return
	 */
	@PostMapping("loadDepartmentTree")
	public JSONResponse<List<DepartmentTreeInfo>> loadDepartmentTree(
			@RequestBody DepartmentInfo departmentInfo) {
		Integer parentId = departmentInfo.getId();
		parentId = parentId == null ? 0 : parentId;
		List<DepartmentTreeInfo> departmentTreeInfoList = departmentService
				.loadDepartmentTree(parentId);
		if (departmentTreeInfoList == null) {
			logger.error("获取部门树结构异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(departmentTreeInfoList);
		}
	}

	/**
	 * @Description: 获得当前父节点的子部门和人员
	 * @author czy
	 * @date 2017年8月15日
	 * @param id
	 *            :部门id,0为顶层节点
	 * @return
	 */
	@PostMapping("loadCurrentDepartmentTree")
	public JSONResponse<List<DepartmentTreeInfo>> loadCurrentDepartmentTree(
			@RequestBody DepartmentInfo departmentInfo) {
		Integer parentId = departmentInfo.getId();
		parentId = parentId == null ? 0 : parentId;
		List<DepartmentTreeInfo> departmentTreeInfoList = departmentService
				.loadCurrentDepartmentTree(parentId);
		if (departmentTreeInfoList == null) {
			logger.error("获取部门树结构异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
			return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
		} else {
			return success(departmentTreeInfoList);
		}
	}
	
	/**
	 * @Description 获取所有有效的部门信息
	 * @author lk
	 * @date 2017年8月30日
	 * @return
	 */
	@PostMapping("listAllDepartment")
    public JSONResponse<List<Department>> listAllDepartment(HttpSession httpSession) {
        List<Department> departmentList = departmentService.listAll();
        if (departmentList == null) {
            logger.error("获取所有部门信息异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
            return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
        } else {
            return success(departmentList);
        }
    }
    
    /**
     * @Description 根据部门ID获取部门详细信息（包括人员列表）
     * @author lk
     * @date 2017年8月31日
     * @param departmentInfo
     * @return
     */
    @RequestMapping("getDetailById")
    public JSONResponse<DepartmentInfo> getDetailById(
            @RequestBody DepartmentInfo departmentInfo) {
        if(departmentInfo.getId() == null) {
            logger.error("获取部门详细信息异常：" + GlobalErrorEnum.UNKNOWN_ERROR.getMsg());
            return new JSONResponse<>(GlobalErrorEnum.UNKNOWN_ERROR);
        } else {
            DepartmentInfo info = departmentService.getDetailInfoById(departmentInfo);
            return success(info);
        }
    }
}
